package com.tqjc.system.C24012.core.service.websocket;

import com.alibaba.fastjson.JSON;
import com.tqjc.system.C24012.common.constant.SystemConstants;
import com.tqjc.system.C24012.common.entity.SysAreaInfoEntity;
import com.tqjc.system.C24012.core.config.websocket.WebSocketConfigurator;
import com.tqjc.system.C24012.core.service.SysAreaInfoService;
import com.tqjc.system.core.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

/**
 * @Author: 86195
 * @CreateTime: 2024-06-28  14:42
 * @Description: 库区信息websocket
 * @Version: 1.0
 */
@ServerEndpoint(value = "/webSocket/areaInfo",configurator = WebSocketConfigurator.class)
@Component("AreaInfoWebSocketService")
@Slf4j
public class AreaInfoWebSocketService {


    private static Map<String, Session> sessionMap = new HashMap<>();



    @OnOpen
    public void onOpen(Session session) throws Exception {
        String ip = (String) session.getUserProperties().get(SystemConstants.STRING_IP);
        Session lastSession = sessionMap.get(ip);
        if(lastSession == null){
            sessionMap.put(ip,session);
            log.info("ip:{},电脑开始连接，发送垛位信息数据",ip);
            SysAreaInfoService service = SpringUtils.getBean(SysAreaInfoService.class);
            List<SysAreaInfoEntity> list = service.list();
            Collections.sort(list);
            //首次连接，响应码为1
            this.sendMessage(this.buildListMessage(list,"响应成功",SystemConstants.HTTPSTATUS_SUCCESS),ip);
            log.info("ip:{},发送垛位信息数据完成",ip);
        }

    }

    @OnClose
    public void onClose(Session session){
        //连接关闭
        String ip = (String) session.getUserProperties().get(SystemConstants.STRING_IP);
        sessionMap.remove(ip);
    }

    @OnError
    public void onError(Throwable error,Session session){
        //连接关闭
        String ip = (String) session.getUserProperties().get(SystemConstants.STRING_IP);
        log.error("TaskMonitorWebSocketService running error");
        sessionMap.remove(ip);
        error.printStackTrace();
    }



    private Map buildListMessage(List data,String msg,String code){
        Map map = new HashMap();
        map.put("data",data);
        map.put("msg",msg);
        map.put("code",code);
        return map;
    }


    public void sendMessage(Map resMap) {

        Map<String,Session> sessionMap = this.sessionMap;

        sessionMap.entrySet().forEach(e -> {
            try {
                e.getValue().getBasicRemote().sendText(JSON.toJSONString(resMap));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
    }

    public void sendMessage(Map resMap,String ip) {
        try {
            Session session = sessionMap.get(ip);
            session.getBasicRemote().sendText(JSON.toJSONString(resMap));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("======sendMessage方法========发送数据出现异常");
        }

    }

    public void sendMessage(List list, String msg, String code) {

        Map<String,Session> sessionMap = this.sessionMap;

        sessionMap.entrySet().forEach(e -> {
            try {
                e.getValue().getBasicRemote().sendText(JSON.toJSONString(this.buildListMessage(list,msg,code)));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
    }

    public  Map getSessionMap(){
        return this.sessionMap;
    }



}
